package com.cheetah.start.common.config;

import com.alibaba.fastjson.JSONObject;
import com.cheetah.start.common.base.result.Result;
import org.noear.solon.Utils;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.validation.ValidatorFailureHandler;

import java.lang.annotation.Annotation;

@Component
public class ValidHandler implements ValidatorFailureHandler {

    @Override
    public boolean onFailure(Context ctx, Annotation ano, org.noear.solon.core.handle.Result result, String message) throws Throwable {
        ctx.setHandled(true);
        ctx.setRendered(true);

        if (Utils.isEmpty(message)) {
            message = new StringBuilder(100)
                    .append("@")
                    .append(ano.annotationType().getSimpleName())
                    .append("verification failed")
                    .toString();
        }

        Result<Object> failure = Result.failure(message);
        String res = JSONObject.toJSONString(failure);

        ctx.output(res);
        return false;
    }
}
